package com.micro.config.Filter;

import com.micro.config.Utils.JwtUtils;
import com.micro.service.Impl.UserDetailsServiceImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsServiceImp userDetailsServiceimp;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String token = "";
        String username = "";
//        获取token的username，获取请求头里面的token，前端将token存在localstorage里面
        for (Cookie cookie : httpServletRequest.getCookies()) {
            if (cookie.getName().equals("username")) {
                username = cookie.getValue();
            }
            if (cookie.getName().equals("token")) {
                token = cookie.getValue();
            }
        }

        if (token.isEmpty() || username.isEmpty()){
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
//        获取用户的详细信息
        UserDetails userDetails = userDetailsServiceimp.loadUserByUsername(username);
        if (JwtUtils.verifyToken(token, username)) {
//            认证成功后创建一个UsernamePasswordAuthenticationToken对象，并将用户详细信息和权限信息传递给它。
            UsernamePasswordAuthenticationToken authentication =
                    new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
//            身份验证时，就可以获取到当前请求的详细信息，如IP地址、请求参数等，以便进行安全验证。
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
//            将创建的认证对象设置到SecurityContextHolder中，以便在整个应用程序中访问
            SecurityContextHolder.getContext().setAuthentication(authentication);
        } else {
            /*
            * 可设置为返回登录页
            * */
            System.out.println(username + "JwtToken验证失败");
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

}
